//
//  ONLoginViewController.m
//  Volatix
//
//  Created by Anh Tran on 6/3/14.
//  Copyright (c) 2014 Familly. All rights reserved.
//

#import "ONLoginViewController.h"
#import "UIView+FormScroll.h"
#import "ONUserLogin.h"

@interface ONLoginViewController ()<UITextFieldDelegate>

@end

@implementation ONLoginViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // remember login
    if ([self userIsLogin]) {
        UITabBarController *tabBarController = [self.storyboard instantiateViewControllerWithIdentifier:@"MainTabbar"];
        tabBarController.navigationItem.hidesBackButton = YES;
        
        [self.navigationController pushViewController:tabBarController animated:NO];
        
        return;
    }
    
    self.emailTextField.text = @"hungtran.it13@gmail.com";
    self.passwordTextField.text = @"123456";
    
    // Do any additional setup after loading the view.
    UITapGestureRecognizer *tapHideKeyboard = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    tapHideKeyboard.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapHideKeyboard];
}

-(void)hideKeyboard{
    [self.view endEditing:YES];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     self.navigationController.navigationBarHidden = YES;
    [_emailTextField setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];    
    [_passwordTextField setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];

    //[[UINavigationBar appearance] setBackgroundColor:[UIColor greenColor]];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:40.0/255.0 green:43.0/255.0 blue:54.0/255.0 alpha:1.0];
    //self.navigationController.navigationBar.translucent = NO;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.view beginKeyBoardAvoidWith:self.view.frame];
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [self.view endKeyBoardAvoid:self.view.frame];
}
//-(void)
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
//- (void) drawPlaceholderInRect:(CGRect)rect {
//    [[UIColor blueColor] setFill];
//    [_emailTextField.placeholder drawInRect:rect withAttributes:];//drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
//}
- (IBAction)loginButtonPressed:(id)sender {
    
    //////------------------------------------------------------------------------------------//
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    [APP_DELEGATE.iServiceEngine LoginByUserName:@"hungtran.it13@gmail.com" Password:@"123456" completed:^(NSDictionary *responseDict) {
//        // NSDictionary *objDic = [Utils objectForKeyNotNull:@"ObjectValue" andDictionnary:responseDict ];
//    
//    
//    } onError:^(NSError *error) {
//        ////
//    }];
    
 //////------------------------------------------------------------------------------------//
    
    [self.view endEditing:YES];
    
    // Check valid email
    BOOL emailIsValid = [Utils validateEmail:self.emailTextField.text];
    
    // Email is valid
    if (emailIsValid) {
        
        // Password is valid
        if ([self.passwordTextField.text length] >= kMinPasswordCharacters) {
                
                // Call webservice to login
                [self requestLoginService];
        } else {
            if([self.passwordTextField.text length] == 0){
                [Utils showAlertViewWithTitle:nil withMessage:PASSWORD_IS_BLANK];
                
            }else{
                [Utils showAlertViewWithTitle:nil withMessage:PASSWORD_IS_INVALID];
            }
        }
    }
 
}

- (void)requestLoginService {
    
    
    NSString *str =[Utils uniqueVendor];
    NSLog(@"%@  -[Utils uniqueVendor] %@",str,[Utils uniqueVendor]);
    NSString * tokenString =[APP_DELEGATE gettingDeviceToken];
    // show loading view
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *formParams = [NSDictionary dictionaryWithObjectsAndKeys:
                                @"password", @"grant_type",
                                self.emailTextField.text, @"userName",
                                self.passwordTextField.text, @"password",
                                (tokenString==nil)?nil:tokenString, @"deviceToken",
                                str, @"instId",
                                nil];
    
    
    [manager POST:[NSString stringWithFormat:@"%@%@",URL_SERVICE,LOGIN] parameters:formParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
        
        ONUserLogin *userLogin = [ONUserLogin modelObjectWithDictionary:responseObject];
        
        if ([userLogin.accessToken length] > 0) {
            [self saveAccessToken:userLogin.accessToken];

            UITabBarController *tabBarController = [self.storyboard instantiateViewControllerWithIdentifier:@"MainTabbar"];
            tabBarController.navigationItem.hidesBackButton = YES;
            
            if (self.navigationController) {
                [self.navigationController pushViewController:tabBarController animated:YES];
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
            
        } else {
            [Utils showAlertViewWithTitle:nil withMessage:WRONG_USERNAME_OR_PASSWORD];
        }

        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [Utils showAlertViewWithTitle:nil withMessage:WRONG_USERNAME_OR_PASSWORD];
        NSLog(@"Error: %@", error);
    }];
}

- (IBAction)skipLoginButtonPressed:(id)sender {
    [self saveAccessToken:nil];
    
    UITabBarController *tabBarController = [self.storyboard instantiateViewControllerWithIdentifier:@"MainTabbar"];
    tabBarController.navigationItem.hidesBackButton = YES;
    
    if (self.navigationController) {
        [self.navigationController pushViewController:tabBarController animated:YES];
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

@end
